# -*- coding: utf-8 -*-
import sys
import json
import urllib
import ldap
import logging
import traceback

from tconfig import *
reload(sys)
sys.setdefaultencoding('utf-8')

logger = logging

def verified_lianjia_core(username):
    # Open a connection
    res = (0, '')
    searchFilter = SEARCH_ATTR+'='+username
    try:
        l = ldap.initialize(LDAP_HOST+':'+LDAP_PORT)
        l.set_option(ldap.OPT_REFERRALS, 0)
        l.protocol_version = ldap.VERSION3
    except ldap.LDAPError as e:
        logger.error("ldap initialize error, "+str(e))
        return res
    try:
        l.simple_bind_s(B_DN, B_DN_PASSWD)
        ldap_result_id = l.search(BASE_DN, ldap.SCOPE_SUBTREE, searchFilter, None)
        result_type, result_data = l.result(ldap_result_id, 2)
        logger.debug(result_data)
        l.unbind()
        if len(result_data) != 0 and isinstance(result_data[0], tuple):
            a, b = result_data[0]
            if isinstance(b, dict):
                res_new = (1, a)
                return res_new
            else:
                return res
        else:
            return res
    except ldap.LDAPError as e:
        logger.error(traceback.format_exc())
        logger.error("ldap search error, "+str(e))
        return res

def verified_lianjia(username, password):
    code = -1
    isfound, result = verified_lianjia_core(username)
    if isfound:
         try:
             l = ldap.initialize(LDAP_HOST+':'+LDAP_PORT)
             l.simple_bind_s(result, password)
             logger.error("user: %s login success" % (username))
             code = 0
         except ldap.LDAPError, e:
             logger.error("user: %s login failed: %s", username, e)
    else:
         logger.debug("user: %s verify failed" % (username))
    return code

if __name__ == "__main__":
    verified_lianjia("zhangxudong01","zhangxd123Q!");